﻿Shader "lijia/water"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_BaseColor("BaseColor", Color) = (1,1,1,1)
		_FresnelBase("FresnelBase", Range(0, 1)) = 0
		_FresnelScale("FresnelScale", Range(0, 1)) = 0
		_FresnelIndensity("_FresnelIndensity", Range(0, 2)) = 1

		_ReflectionTex ("_ReflectionTex", 2D) = "white" {}

		_L("波长 L", float) = 1
		_A("振幅 A", float) = 1
		_S("传播的速度 S", float) = 1
		_D("波浪传播的方向 D", float) = 1
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" "queue"="transparent"}
		LOD 100
		GrabPass{}
		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"
			#include "Lighting.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
				float4 proj : TEXCOORD1;
				float3 L : TEXCOORD2;
				float3 V : TEXCOORD3;
				float4 proj2 : TEXCOORD4;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;

			float4 _BaseColor;

			float _FresnelBase;
			float _FresnelScale;
			float _FresnelIndensity;

			sampler2D _GrabTexture;

			sampler2D _ReflectionTex;

			float _L;
			float _A;
			float _S;
			float _D;

			v2f vert (appdata_tan v)
			{
				v2f o;

				float w = 2*3.14159 / _L;
				float f = _S * w;
				v.vertex.y += _A * sin( _D * length(v.vertex.xz) * w + _Time.x * f);

				o.vertex = UnityObjectToClipPos(v.vertex);

				o.uv = TRANSFORM_TEX(v.texcoord.xy, _MainTex);
				o.proj = ComputeGrabScreenPos(o.vertex);
				o.proj2 = ComputeScreenPos(o.vertex);
				o.L = ObjSpaceLightDir(v.vertex);
				o.V = ObjSpaceViewDir(v.vertex);
				TANGENT_SPACE_ROTATION;//要把光转到切线空间（纹理空间）才能跟法向量计算

				o.L = mul(rotation, o.L);
				o.V = mul(rotation, o.V);
				return o;
			}

			fixed4 frag (v2f i) : SV_Target
			{
				fixed4 col1 = tex2D(_MainTex, i.uv + float2(_Time.x, 0));

				fixed4 col2 = tex2D(_MainTex, i.uv + float2(1-i.uv.y, i.uv.x) + float2(_Time.x, 0));

				fixed4 col = (col1 + col2)/2;

				float3 N = normalize(UnpackNormal(col));
				float3 L = normalize(i.L);
				float3 V = normalize(i.V);

				float offset = dot(N, float3(0,1,0));//不明白，为什么要跟向上的垂直向量做点乘

				i.proj.xy += offset;

				fixed4 grabCol = tex2Dproj(_GrabTexture, i.proj);
				//漫反射
				float diff = max(0, dot(N, L));
				//半角向量
				float3 H = normalize(L + V);
				float spc = pow(max(0, dot(H, N)), 128);
				i.proj2.xy += offset;
				fixed4 reflec = tex2Dproj(_ReflectionTex, i.proj2);

				float4 diffCol = reflec;
				diffCol.rgb += spc * _LightColor0.rgb;//加上镜面高光

				float fresnel = _FresnelBase + _FresnelScale * pow(1 - max(0, dot(N, V)), _FresnelIndensity);

				float4 finalCol = lerp(grabCol, diffCol, fresnel);
				return finalCol;
			}
			ENDCG
		}
	}
}
